import java.util.LinkedList;
import java.util.Queue;

public class LC_116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
    public Node connect(Node root) {
        Queue<Node> que = new LinkedList<>();
        int size = 1;
        if(root == null){
            return root;
        }
        que.offer(root);
        while(!que.isEmpty()){
            int len = size;
            size = 0;
            while(len != 0){
                len--;
                Node node = que.poll();
                if(len != 0){
                    node.next = que.peek();
                }else{
                    node.next = null;
                }
                if(node.left != null){
                    size++;
                    que.offer(node.left);
                }
                if(node.right != null){
                    size++;
                    que.offer(node.right);
                }
            }

        }
        return root;
    }
}
